//
//  HNSH_BusinessCircleDetailAlert.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/9/26.
//

#import "HNSH_BusinessCircleDetailAlert.h"
#import "HNSH_PopupController.h"
#import "HNSH_ShopNetServer.h"

#import "HNSH_AuthTool.h"

@interface HNSH_BusinessCircleDetailAlert ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

/* nyPopView */
@property(nonatomic, strong) HNSH_PopupController *nyPopView;

/* okButton */
@property (nonatomic, strong) UIButton *okButton;
/* cancelButton */
@property (nonatomic, strong) UIButton *cancelButton;
/* titleLabel */
@property (nonatomic, strong) UILabel *titleLabel;

/* pzButton */
@property (nonatomic, strong) UIButton *pzButton;

/* shopId */
@property (nonatomic, copy) NSString *shopId;
/* amount */
@property (nonatomic, copy) NSString *amount;
/* image_url */
@property (nonatomic, copy) NSString *image_url;
@end

@implementation HNSH_BusinessCircleDetailAlert


- (instancetype)initWithFrame:(CGRect)frame shopId:(NSString *)shopId {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.shopId = shopId;
        self.amount = @"";
        [self configUI];
    }
    return self;
}

- (void)showView {
    self.nyPopView = [[HNSH_PopupController alloc]init];
    self.nyPopView.dismissOnMaskTouched = NO;
    self.nyPopView.layoutType = PopupLayoutTypeCenter;
    self.nyPopView.slideStyle = PopupSlideStyleFade;
    [self.nyPopView presentContentView:self duration:0.25 springAnimated:YES inView:kSTWindow];
    self.nyPopView.popupView.layer.cornerRadius = 16.0f;
    self.nyPopView.popupView.layer.masksToBounds = YES;
}

- (void)closeView {
    [self.nyPopView dismissWithDuration:0.25 springAnimated:YES];
}

- (void)configUI {
    [self addSubview:self.titleLabel];
    [self addSubview:self.okButton];
    [self addSubview:self.cancelButton];
    
    [self configInputXFJE];
    [self configUpLoadImage];
}

//输入消费金额
- (void)configInputXFJE {
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(16, 58, self.width-32, 50)];
    bgView.backgroundColor = [UIColor appBGColor];
    bgView.layer.cornerRadius = 8.0f;
    bgView.layer.masksToBounds = YES;
    [self addSubview:bgView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 0, 70, bgView.height)];
    titleLabel.textColor = [UIColor appBlackLabelColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.text = @"消费金额：";
    [bgView addSubview:titleLabel];
    
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(82, 0, bgView.width-100, bgView.height)];
    textField.placeholder = @"请输入实际消费金额";
    textField.textColor = [UIColor appBlackLabelColor];
    textField.font = [UIFont boldSystemFontOfSize:14];
    [bgView addSubview:textField];
    WeakSelf(weakSelf);
    [[textField rac_signalForControlEvents:UIControlEventEditingChanged] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UITextField *field = x;
        weakSelf.amount = field.text;
    }];
}

//上传凭证
- (void)configUpLoadImage {
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(16, 120, self.width-32, 168)];
    bgView.backgroundColor = [UIColor appBGColor];
    bgView.layer.cornerRadius = 8.0f;
    bgView.layer.masksToBounds = YES;
    [self addSubview:bgView];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 15, 70, 20)];
    titleLabel.textColor = [UIColor appBlackLabelColor];
    titleLabel.font = [UIFont systemFontOfSize:14];
    titleLabel.text = @"付款截图：";
    [bgView addSubview:titleLabel];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"b_circle_detail_add"] forState:UIControlStateNormal];
    button.frame = CGRectMake(bgView.width/2-40, 45, 80, 80);
    [bgView addSubview:button];
    self.pzButton = button;
    WeakSelf(weakSelf);
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf chooseImage];
    }];
    
    
    UILabel *desLabel = [[UILabel alloc]initWithFrame:CGRectMake(12, 132, bgView.width-24, 20)];
    desLabel.textColor = [UIColor appGrayLabelColor];
    desLabel.font = [UIFont systemFontOfSize:14];
    desLabel.text = @"请上传付款截图";
    desLabel.textAlignment = NSTextAlignmentCenter;
    [bgView addSubview:desLabel];
}

//提交信息
- (void)loadBusinessCircleUploadVoucher {
    if(![self.amount isNotBlank]) {
        [kSTWindow makeToast:@"请输入实际消费金额"];
        return;
    }
    if(![self.image_url isNotBlank]) {
        [kSTWindow makeToast:@"请上传图片"];
        return;
    }
    [HNSH_ShopNetServer requestBusinessCircleUploadVoucherWithShopId:self.shopId amount:self.amount image_url:self.image_url success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self closeView];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 上传图片
- (void)chooseImage{
    UIAlertController * alertSheet = [UIAlertController alertControllerWithTitle:@"修改头像" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestCameragraph:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypeCamera];
            } else {
                [kSTWindow makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [HNSH_AuthTool requestForPhotoAuth:^(BOOL isAuth) {
            if (isAuth) {
                [self startChooseImage:UIImagePickerControllerSourceTypePhotoLibrary];
            } else {
                [kSTWindow makeToast:@"未获得权限，无法上传图片"];
            }
        }];
    }]];
    [alertSheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:alertSheet animated:YES completion:nil];
}

- (void)startChooseImage:(UIImagePickerControllerSourceType)sourceType{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.allowsEditing = YES;
    imagePicker.delegate = self;
    imagePicker.sourceType = sourceType;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [[UIViewControllerHelper findCurrentShowingViewController] presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        NSData * data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage], 0.5);
        if (!data) {
            data = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.5);
        }
        [self commitImgToAliyunOSS:data];
    }];
}


//MARK: 上传图片到七牛
- (void)commitImgToAliyunOSS:(NSData *)imgData{
    UIImage * image = [UIImage imageWithData:imgData];
    [ST_BaseNetManager uploadImageWithImageData:image progress:^(NSString *key, float percent) {
        
    } complate:^(NSString * _Nonnull urlString) {
        if (urlString && urlString.length) {
            self.image_url = urlString;
            [self.pzButton sd_setImageWithURL:[NSURL URLWithString:urlString] forState:UIControlStateNormal];
        }
    }];
}

#pragma mark lazy
- (UIButton *)okButton {
    if (!_okButton) {
        _okButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _okButton.frame = CGRectMake(32+(self.width-48)/2, 312, (self.width-48)/2, 40);
        [_okButton setTitle:@"确定" forState:UIControlStateNormal];
        [_okButton setTitleColor:[UIColor appWhiteLabelColor] forState:UIControlStateNormal];
        _okButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _okButton.backgroundColor = [UIColor appGreenColor];
        _okButton.layer.cornerRadius = 20.0f;
        _okButton.layer.masksToBounds = YES;
        WeakSelf(weakSelf);
        [[_okButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf loadBusinessCircleUploadVoucher];
        }];
    }
    return _okButton;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(16, 312, (self.width-48)/2, 40);
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor appBlackLabelColor] forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _cancelButton.backgroundColor = [UIColor appBGColor];
        _cancelButton.layer.cornerRadius = 20.0f;
        _cancelButton.layer.masksToBounds = YES;
        WeakSelf(weakSelf);
        [[_cancelButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf closeView];
        }];
    }
    return _cancelButton;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 16, self.width-32, 22)];
        _titleLabel.textColor = [UIColor appBlackLabelColor];
        _titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text = @"上传支付凭证";
    }
    return _titleLabel;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
